import React, { useState, useEffect } from 'react';
import { Form, Input, Button, Radio, Space, message } from 'antd';
import { SyncOutlined, ReloadOutlined } from '@ant-design/icons';
import { useRequest } from 'ahooks';
import Modals from '@/components/modals/Modals';
import nl2sqlService from '@/api/services/nl2sqlService';
import { TableColumn, GetColumnEnumRequest } from '@/types/nl2sql/type';

import '../styles/index.scss';

interface ColumnEditModalProps {
  visible: boolean;
  onCancel: () => void;
  onOk: (values: any) => void;
  column: TableColumn | null;
  tableId: string;
  databaseId: string;
}

const ColumnEditModal: React.FC<ColumnEditModalProps> = ({
  visible,
  onCancel,
  onOk,
  column,
  tableId,
  databaseId,
}) => {
  const [form] = Form.useForm();
  const [enumValues, setEnumValues] = useState<string[]>([]);
  const [examples, setExamples] = useState<string[]>([]);
  const [isEnum, setIsEnum] = useState<boolean>(false);
  const [examplesInput, setExamplesInput] = useState<string>('');

  // 同步枚举候选值接口
  const { run: syncEnumValues } = useRequest(
    async () => {
      if (!column?.column_name) return;

      const requestData: GetColumnEnumRequest = {
        database_id: databaseId,
        update_status: 'add',
      };

      const response = await nl2sqlService.getColumnEnum(
        tableId,
        column.column_name,
        requestData
      );

      setEnumValues(response);
      message.success('枚举候选值同步成功');
    },
    {
      manual: true,
      onError: (error) => {
        message.error('同步枚举候选值失败');
        console.error('同步枚举候选值失败:', error);
      },
    }
  );

  // 初始化表单数据
  useEffect(() => {
    if (visible && column) {
      const isEnumValue = column.is_enum || false;
      form.setFieldsValue({
        column_zh_name: column.column_zh_name || '',
        column_description: column.column_description || '',
        data_type: column.data_type || '',
        is_enum: isEnumValue,
      });

      setIsEnum(isEnumValue);
      setEnumValues(column.enum_values || []);
      setExamples(column.examples || []);
      setExamplesInput((column.examples || []).join('，'));
    }
  }, [visible, column, form]);

  // 处理确认
  const handleOk = async () => {
    try {
      const values = await form.validateFields();

      // 将逗号分隔的字符串转换为数组
      const examplesArray = examplesInput
        .split(/[,，]/)
        .map(item => item.trim())
        .filter(item => item.length > 0);

      const result = {
        ...values,
        enum_values: enumValues,
        examples: examplesArray,
      };

      onOk(result);
    } catch (error) {
      console.error('表单验证失败:', error);
    }
  };

  // 处理取消
  const handleCancel = () => {
    form.resetFields();
    setIsEnum(false);
    setEnumValues([]);
    setExamples([]);
    onCancel();
  };

  // 恢复初始化信息
  const handleRestore = () => {
    if (column) {
      const isEnumValue = column.is_enum || false;
      form.setFieldsValue({
        column_zh_name: column.column_zh_name || '',
        column_description: column.column_description || '',
        data_type: column.data_type || '',
        is_enum: isEnumValue,
      });
      setIsEnum(isEnumValue);
      setEnumValues(column.enum_values || []);
      setExamples(column.examples || []);
      setExamplesInput((column.examples || []).join('，'));
      message.success('已恢复初始化信息');
    }
  };

  // 处理是否枚举变化
  const handleEnumChange = (value: boolean) => {
    console.log('value', value);
    form.setFieldValue('is_enum', value);
    setIsEnum(value);
  };

  return (
    <Modals
      title={`${column?.column_name || ''}列编辑`}
      open={visible}
      onCancel={handleCancel}
      width={600}
      footer={null}
      destroyOnHidden={true}
      maskClosable={false}
      modelContentClassName="!p-0 mx-3"
    >
      <div className="p-1">
        <Form
          form={form}
          layout="vertical"
          initialValues={{
            column_description: '',
            data_type: '',
            is_enum: false,
          }}
        >
          {/* 列描述 */}
          <Form.Item
            label="列中文名"
            name="column_zh_name"
            rules={[
              // { required: true, message: '请输入列中文名' }
            ]}
          >
            <Input
              placeholder="请输入列中文名"
              className="bg-gray-50"
            />
          </Form.Item>
          {/* 列描述 */}
          <Form.Item
            label="列描述"
            name="column_description"
            rules={[
              // { required: true, message: '请输入列描述' }
            ]}
          >
            <Input.TextArea
              rows={3}
              placeholder="请输入列描述"
              showCount
              maxLength={500}
            />
          </Form.Item>

          {/* 数据类型 */}
          <Form.Item
            label="数据类型"
            name="data_type"
          >
            <Input
              placeholder="数据类型"
              disabled
              className="bg-gray-50"
            />
          </Form.Item>

          {/* 是否枚举 */}
          <Form.Item
            label="是否枚举"
            name="is_enum"
          >
            <Radio.Group onChange={(e) => handleEnumChange(e.target.value)}>
              <Radio value={true}>是</Radio>
              <Radio value={false}>否</Radio>
            </Radio.Group>
          </Form.Item>

          {/* 枚举类型候选值 - 仅当选择"是"时显示 */}
          {isEnum && (
            <Form.Item
              className="w-full label-w-full"
              label={
                <div className="flex w-full items-center justify-between">
                  <span>枚举类型候选值</span>
                  <div>
                    <Button
                      type="link"
                      size="small"
                      icon={<SyncOutlined />}
                      onClick={syncEnumValues}
                      className="p-0 h-auto text-blue-600 hover:text-blue-800"
                    >
                      同步该列枚举候选值
                    </Button>
                  </div>
                </div>
              }
            >
              <div className="min-h-[80px] p-3 border border-gray-200 rounded-md bg-gray-50">
                {enumValues.length > 0 ? (
                  <div className="space-y-1">
                    <div className="text-sm text-gray-700">
                      {enumValues.join('，')}
                    </div>
                    {/* {enumValues.map((value, index) => (
                      <div key={index} className="text-sm text-gray-700">
                        {value}
                      </div>
                    ))} */}
                  </div>
                ) : (
                  <div className="text-sm text-gray-400 text-center py-4">
                    暂无枚举候选值，点击同步按钮获取
                  </div>
                )}
              </div>
            </Form.Item>
          )}

          {/* 数据样例 */}
          <Form.Item
            label={
              <div className="flex items-center">
                <span>数据样例</span>
              </div>
            }
          >
            <Input.TextArea
              rows={3}
              placeholder="请输入数据样例，多个样例用逗号分隔"
              value={examplesInput}
              onChange={(e) => setExamplesInput(e.target.value)}
              className="mb-2"
            />
            {/* <div className="min-h-[80px] p-3 border border-gray-200 rounded-md bg-gray-50">
              {examplesInput.trim() ? (
                <div className="space-y-1">
                  <div className="text-sm text-gray-700">
                    {examplesInput.split(/[,，]/).map((item, index) => (
                      <span key={index} className="inline-block bg-blue-100 text-blue-800 px-2 py-1 rounded mr-2 mb-1">
                        {item.trim()}
                      </span>
                    ))}
                  </div>
                </div>
              ) : (
                <div className="text-sm text-gray-400 text-center py-4">
                  暂无数据样例，请输入数据样例
                </div>
              )}
            </div> */}
          </Form.Item>

          {/* 操作按钮 */}
          <Form.Item className="mb-0">
            <div className="flex items-center justify-between mt-4 pt-4">
              <Button
                icon={<ReloadOutlined />}
                onClick={handleRestore}
                className="text-gray-600 hover:text-gray-800"
              >
                恢复初始化信息
              </Button>

              <Space>
                <Button onClick={handleCancel}>
                  取消
                </Button>
                <Button type="primary" onClick={handleOk}>
                  确认
                </Button>
              </Space>
            </div>
          </Form.Item>
        </Form>
      </div>
    </Modals>
  );
};

export default ColumnEditModal; 